const { Video, Videocomment,Videolike,Subscribe,Collect } = require("../model"); // requie加载文件时 就会执行加载的js
const mongoose = require("mongoose");
const { hotInc,getHotInc } = require('../model/redis/redishotInc')

//获取某几条热门视频
const getHotVideo = async (req,res)=>{
  const num = req.params.num
  const topRes = await getHotInc(num)
  res.status(200).json({topRes,msg:'获取数据成功',code:200})
}
// 视频推荐: redis值 观看+1 点赞+2 评论+2  收藏+3 
// 入参 {videoId:""}
// 收藏视频
const collectvideo = async (req,res)=>{
  // 1.查询视频库里是否有该视频
  // 2.判断是否被收藏郭
  const { videoId } = req.params;
  const userId = req?.user?.userInfo?._id
  const isValidId = mongoose.Types.ObjectId.isValid(videoId) //查询验证id的合理性 避免误传导致的抛错
  if (!isValidId) return res.status(400).send("id is not valid")

  const isHave = await Video.findById(videoId)
  if(!isHave){
    return res.status(404).json({code:500,msg:'该视频不存在!!!'})
  }
  const isCollect = await Collect.findOne({user:userId,video:videoId})
  if(isCollect){
    return res.status(404).json({msg:"视频已被收藏了"})
  }else{
    await new Collect({
      user:userId,
      video:videoId
    }).save()
    await hotInc(videoId,3)
    return res.status(200).json({code:200,msg:'收藏成功!!'})
  }
}

// 入参 {title:'',vodvideoId:''} 返回 json相关数据
// 视频入库接口 ps:将上传到阿里云视频点播服务的视频 进行入库
const createVideos = async (req, res) => {
  try {
    let body = req.body;
    body.user = req?.user?.userInfo?._id;
    const videoModel = new Video(body);
    const backJson = await videoModel.save();
    res.status(200).json(backJson);
  } catch (error) {
    res.status(500).json({ error });
  }
};

//获取 入库视频的列表 分页接口
// 入参 当前页码 每页数量
const videoLists = async (req, res) => {
  try {
    const { pageSize = 10, pageSkip = 1 } = req.body;
    const SkipCount = (pageSkip - 1) * pageSize; //需要跳过的数量
    const backJson = await Video.find()
      .skip(SkipCount)
      .limit(pageSize)
      .sort({ createAT: -1 })
      .populate("user", "_id username cover imgage"); // sort倒序 populate过滤只需要的参数
    const videoAllCount = await Video.countDocuments();
    res.status(200).json({ data: backJson, videoAllCount });
  } catch (error) {
    res.status(500).json({ error });
  }
};

//获取某条视频详情
const video = async (req, res) => {
  try {
    const { videoId } = req.params; //获取get请求url上拼接的参数 将数据库中_id的值作为参数
    let videoInfo = await Video.findById(videoId).populate(
      "user",
      "_id username cover"
    );
  videoInfo = videoInfo.toJSON()
  videoInfo.islike = false
  videoInfo.isDislike = false
  videoInfo.isSubscribe = false

  //补充 某个视频详情的 订阅 喜欢 不喜欢等状态
  if (req.user.userInfo) {
    const userId = req.user.userInfo._id
    if (await Videolike.findOne({ user: userId, video: videoId, like: 1 })) {
      videoInfo.islike = true
    }
    if (await Videolike.findOne({ user: userId, video: videoId, like: -1 })) {
      videoInfo.isDislike = true
    }
    if (await Subscribe.findOne({ user: userId, channel: videoInfo.user._id })) {
      videoInfo.isSubscribe = true
    }
  }
    await hotInc(videoId,1)
    res.status(200).json({ data: videoInfo });
  } catch (error) {
    console.log(error,'===== error ======');
    res.status(500).json({ error });
  }
};

//视频评论
// 1.查找相关视频 没有则提示
// 2.存储评论相关信息到评论数据表中，并将Video表中的评论数量+1
const comment = async (req, res) => {
  const user = req.user.userInfo._id;
  const videoId = req.params.videoId;
  const videoData = await Video.findById(videoId);
  if (!videoData) {
    return res.status(400).json({ msg: "视频不存在!!!" });
  }
  //存储评论到评论表
  const comment = await new Videocomment({
    user,
    video: videoId,
    content: req.body.content,
  }).save();
  videoData.commentCount++;
  videoData.save();
  await hotInc(videoId,2)
  res.status(200).json({ msg: "评论成功", comment });
};

//视频评论列表
const commentLists = async (req, res) => {
  try {
    const { pageNum = 1, pageSize = 10 } = req.query; // 📢注意是 req.query 还是 req.params(常使用路径参数 /:videoId 这种用法)
    const commentLists = await Videocomment.find()
      .skip((pageNum - 1) * pageSize)
      .limit(pageSize)
      .populate("user", "_id username email phone");
    const commentCount = await Videocomment.countDocuments();
    res.status(200).json({ commentLists, commentCount });
  } catch (error) {
    res.status(500).json({ error });
  }
};

//删除评论列表的某条评论
// 1.校验视频是否存在 2.校验评论是否存在 3.只允许本人删除自己评论 4.删除评论表中数据，并将视频表中的值-1
const deletecomment = async (req, res) => {
 try {
  const { videoId, commentId } = req.params;
  const video = await Video.findById(videoId) //findById找的是_id 主键id
  if(!video){
    return res.status(400).json({msg:'视频不存在!'})
  }
  const comment = await Videocomment.findById(commentId)
  if(!comment){
    return res.status(400).json({msg:'视频评论不存在!'})
  }
  //校验是否是本人 本人才允许删除评论
  if(comment.user.equals(req.user.userInfo._id)){ //video拿到的user是mongoose ObjectId是一个对象，使用equals 用来转化比较是否相等
    comment.remove() //删除
    video.commentCount--
    video.save()
    res.status(200).json({msg:'删除评论成功~'})
  }else{
    res.status(400).json({msg:"不允许删除"})
  }
 } catch (error) {
    res.status(500).json({error})
 }
};

//喜欢频道
//1.判断频道是否存在 2.判断喜欢频道的表中是否已经有值了 有的话根据条件取反，没有的话入库保存默认喜欢 3.更新video表中 喜欢和不喜欢的视频的值，统计表中所有的数据
const likevideo = async (req,res)=>{
  const videoId = req.params.videoId
  const videoInfo = await Video.findById(videoId)
  if(!videoInfo){
    return res.status(400).json({msg:'视频不存在!!'})
  }
  const videolike = await Videolike.findOne({
      user:req.user.userInfo._id,
      video:videoId
  })
  let islike = true //设置默认喜欢的状态
  if(videolike && videolike.like==1){
     await videolike.remove()
     islike = false
  }else if(videolike && videolike.like==-1){
    videolike.like = 1
    await videolike.save()
    await hotInc(videoId,2)
  }else{ //什么都没有直接保存默认是喜欢
    await new Videolike({
      user:req.user.userInfo._id,
      video:videoId,
      like:1
    }).save()
  }
  // 统计喜欢和不喜欢的数量并更新
  const likeCount = await Videolike.countDocuments({video:videoId,like:1})
  const dislikeCount = await Videolike.countDocuments({video:videoId,like:-1})

  videoInfo.likeCount = likeCount
  videoInfo.dislikeCount = dislikeCount
  await videoInfo.save()
  res.status(200).json({...videoInfo.toJSON(),islike}) // toJSON 将mongoose文档对象转为JSON对象
}

// 不喜欢频道
const dislikevideo = async (req,res)=>{
  const userId = req.user.userInfo._id
  const videoId = req.params.videoId
  const videoInfo = await Video.findById(videoId)
  if(!videoInfo){
    return res.status(400).json({msg:'频道不存在!'})
  }
  // 查询 喜欢的表 是否存在
  const videolike = await Videolike.findOne({
    user:userId,
    video:videoId
  })
  let isdislike = true
  if(videolike && videolike.like==-1){
    videolike.remove()
    isdislike = false
  }else if(videolike && videolike.like==1){
     videolike.like = -1
     videolike.save()
  }else{
    await new Videolike({
      user:userId,
      video:videoId,
      like:-1
    }).save()
  }
  //更新video中 likeCount和dislikeCount的值
  videoInfo.likeCount = await Videolike.countDocuments({video:videoId,like:1})
  videoInfo.dislikeCount = await Videolike.countDocuments({video:videoId,like:-1})
  videoInfo.save()
  res.status(200).json({...videoInfo.toJSON(),isdislike})
}
const likelist = async (req, res) => {
  const { pageNum = 1, pageSize = 10 } = req.query
  const likes = await Videolike.find({
    like: 1,
    user: req.user.userInfo._id
  }).skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .populate('video', "_id title vodvideoId user")

  var likeCount = await Videolike.countDocuments({
    like: 1,
    user: req.user.userInfo._id
  })
  res.status(200).json({ likes, likeCount })
}

module.exports = {
  createVideos,
  videoLists,
  video,
  comment,
  commentLists,
  deletecomment,
  likevideo,
  collectvideo,
  dislikevideo,
  likelist,
  getHotVideo
};
